# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        max_len, _ = self.findMax(root)
        return max_len
    
    def findMax(self, node):
        max_len, max_depth = 0, 0
        if not node.left and not node.right:
            return max_len, max_depth
        left_len, left_depth = 0, 0
        if node.left:
            left_len, left_depth = self.findMax(node.left)
            left_depth += 1
        right_len, right_depth = 0,0
        if node.right:
            right_len, right_depth = self.findMax(node.right)
            right_depth += 1
        max_depth = max([left_depth, right_depth])
        max_len = max([left_len, right_len])
        if left_depth + right_depth > max_len:
            max_len = left_depth + right_depth
        return max_len, max_depth
